/*  
  -- The Lime II Project -- 

  A tuplespaces-based middleware for coordinating agents and mobile hosts.
  Copyright (C) 2005.
  Gian Pietro Picco, Amy L. Murphy, Lorenzo Bellini.

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  Lesser General Public License for more details.

  You should have received this copy of the GNU Lesser General Public
  License along with this library; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 
*/
 
package testing;
import lime2.*; 
import lights.adapters.*;
import lights.interfaces.*;
import java.util.Random;

/**
 * This agent installs a once-per-tuple strong reaction wrt <code>String</code> template: the reaction keeps track of
 * how many times it fires; after firing 3 times, it uninstalls itself.
 *  
 * @author Gian Pietro Picco
 * @author Amy Murphy
 * @author Lorenzo Bellini
 */

public class InstAndRem implements Runnable, ReactionListener 
{
 //	identification number	
 private int id = new Random().nextInt(1000);		
 
 // private data members
 private int counter = 0;
 private ReactionID[] rw;
 private LimeTupleSpace lts = LimeTupleSpace.get("testing");
 
 /**
  * Run method.
  */
 public void run()
 {
  System.out.println("InstAndRem " + id + ": started");   
  ITuple pattern = new Tuple().add(new Field().setType(String.class));
  LimeTemplate template = new LimeTemplate(Location.HERE, Location.UNSPECIFIED, pattern);
  Reaction r = new Reaction(Reaction.ONCEPERTUPLE, template, this);
  rw = lts.addStrongReaction(new Reaction[] {r});
  System.out.println("InstAndRem " + id + ": reaction installed");     
  System.out.println("InstAndRem " + id + ": dies");
 }
 
 /**
  * Reactive Method.
  * 
  * @param re ReactionEvent
  */
 public void reactsToOut(ReactionEvent re)
 {	
  counter++;
  System.out.println("InstAndRem " + id + ": reaction fired " + counter + " times");
  if (counter == 3)  
  {	
   boolean[] b = lts.removeStrongReaction(rw);
   for (int i = 0; i < b.length && b[i]; i++) b[0] = b[i];
   if (b[0]) System.out.println("InstAndRem " + id + ": reaction successfully uninstalled"); 
        else System.out.println("InstAndRem " + id + ": reaction not successfully uninstalled"); 
  }
 }

@Override
public void reactsToTake(ReactionEvent re) {
	// TODO Auto-generated method stub
	
}
 
}